/**
 * description:js常用方法
 * */
import Type from './lib/Type';
let typeLib=new Type();

/* TODO 判断数据类型 */
export const isString=(value)=>{
    return typeLib.checkType(value)==='string';
}
export const isArray=(value)=>{
    return typeLib.checkType(value)==='array';
}
export const isObject=(value)=>{
    return typeLib.checkType(value)==='object';
}
export const getType=(value)=>{
    return typeLib.checkType(value);
}
/* TODO 转为驼峰 hello-world转为helloWorld */
export const toHump=(str)=>{
    if(!isString(str)){
        throw new Error(`toHump数据格式错误，仅支持string类型数据！`);
    }
    return str.replace(/-(\w)/,($0,$1)=>{
        return $1.toUpperCase();
    });
};
/* todo 首字母大写 index——Index */
export const firstToUpper=(str)=>{
    if(!isString(str)){
        throw new Error(`firstToUpper数据格式错误，仅支持string类型数据！`);
    }
    return str.replace(/\w/,($0)=>{
        return $0.toUpperCase();
    });
}
/* TODO 下载 */
/* todo form跳转 */
/*
* description：form表单下载文件
* @props：
*   url<String>：下载地址。protocol://hostname:port/filepath
*   params<Object>：下载时传递参数。
*   target<String>：新窗口还是本窗口打开。_blank/_self/_parent/_top/frameName
*   type<String>：请求方式。get/post
* */
export const gotoByForm=(url, params = {}, target, type)=> {
    let _newDOM;
    if (!document.downloadForm) {
        _newDOM = document.createElement('form');
        _newDOM.name = 'downloadForm';
        document.body.appendChild(_newDOM);
    } else {
        _newDOM = document.downloadForm;
    }
    _newDOM.target = target || '_self';
    _newDOM.action = url;
    _newDOM.method = type || 'get';
    for (let i = 0; i < _newDOM.childNodes.length; i++) {
        _newDOM.removeChild(_newDOM.childNodes[i]);
        i--;
    }
    for (let keys in params) {
        let childDOM = document.createElement('input');
        childDOM.type = 'text';
        childDOM.name = keys;
        childDOM.value = params[keys];
        _newDOM.appendChild(childDOM);
    }
    _newDOM.style.display = 'none';
    _newDOM.submit();
}
/* todo 带参数下载 */
export const download=(url='',params={},type='post')=> {
    if(!window.frames['download']){
        let elemIF = document.createElement("iframe");
        elemIF.name = 'download';
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
    }
    gotoByForm(url,params,'download',type);
};
